<template>
  <a-card>
    <a-row>
      <a-col :span="12">
        <a-button type="primary" @click="add">添加文章</a-button>
      </a-col>
      <a-col :span="12">
        <a-row type="flex" justify="end">
          <a-select
            class="article-type"
            allow-clear
            v-model:value="articleType.articleType"
            placeholder="文章类型"
            @change="resetPage"
          >
            <a-select-option value="1">平台文章</a-select-option>
            <a-select-option value="2">外部链接</a-select-option>
          </a-select>
          <a-input-search
            v-model:value="articleType.keywords"
            style="width: 210px"
            placeholder="请输入文章标题"
            @search="resetPage"
          />
        </a-row>
      </a-col>
    </a-row>
    <div class="line"></div>
    <a-table
      :columns="columns"
      :data-source="state.dataSource"
      :row-selection="rowSelection"
      :loading="state.loading"
      :pagination="false"
      rowKey="id"
    >
      <!-- 文章类型 -->
      <template #articleType="{ record }">
        <span>
          {{ listMap[record.articleType] }}
        </span>
      </template>

      <!-- 浏览次数 -->
      <template #scanNum="{ record }">
        <span>
          <i class="iconfont icon-guankanshu-16px"></i>
          {{ record.scanNum || 0 }}
        </span>
      </template>

      <!-- 同意次数 -->
      <template #thumbsUp="{ record }">
        <span>
          <i class="iconfont icon-dianzan-16px"></i>
          {{ record.thumbsUp || 0 }}
        </span>
      </template>

      <!-- 反对次数 -->
      <template #thumbsDown="{ record }">
        <span>
          <i class="iconfont icon-fandui-32px"></i>
          {{ record.thumbsDown || 0 }}
        </span>
      </template>

      <!-- 文章添加时间 -->
      <template #createTime="{ record }">
        <span>
          {{ record.createTime }}
        </span>
      </template>

      <!-- 引用位置 -->
      <template #referPosition="{ record }">
        <span>{{ record.referPosition }}</span>
        <a-popover placement="bottomRight" trigger="click">
          <template #content>
            <relevance-table :articleId="record.id"></relevance-table>
          </template>
          <i class="iconfont icon-xiayi12px"></i>
        </a-popover>
      </template>

      <!-- 操作 -->
      <template #handler="{ record }">
        <a @click="edit(record.id)">编辑</a>
        <span style="color: #1890ff; margin: 0 6px">|</span>
        <a @click="delArticle('one', record)">删除</a>
      </template>
    </a-table>

    <a-row style="margin-top: 20px" type="flex" justify="end">
      <a-pagination
        show-quick-jumper
        showSizeChanger
        v-model:pageSize="pagination.limit"
        v-model:current="pagination.page"
        :total="pagination.total"
        :showTotal="() => `共 ${pagination.total} 条数据`"
        @change="getList"
        @showSizeChange="getList"
      />
    </a-row>
    <a-row
      type="flex"
      justify="space-between"
      align="middle"
      style="width: 170px; margin-top: 20px"
    >
      <span>
        已选
        <span style="color: #08c">{{ selRows.length }}</span>
        条
      </span>
      <a-button @click="delArticle('batch')">批量删除</a-button>
    </a-row>
  </a-card>
  <!-- 文章操作 -->
  <article-info
    v-model:visible="showArticleDraw"
    :edit-info="articleForm"
    @get-list="getList"
  ></article-info>
  <!-- 删除文章 -->
  <warning-modal
    title="删除文章"
    content="删除文章"
    v-model:visible="delArticleWarning"
    @confirm="confirmDelArticle"
  >
    <a-row type="flex" justify="center" style="color: #8d8d8d">
      共删除
      <span style="color: #08c">{{ delCount }}</span>
      篇文章，删除后与文章关联关系将全部接触，确定删除吗？
    </a-row>
  </warning-modal>
</template>

<script>
import { reactive, defineComponent, ref } from 'vue';
import relevanceTable from './components/relevanceTable';
import articleInfo from './components/articleInfo';
import WarningModal from '@/components/warning-modal';
import { apiGetArticleList, apiDelArticle, apiGetArticleDetail } from '@/api/articleManage';
import { message } from 'ant-design-vue';
import { parseTime } from '@/utils';
import { concatIds } from '@/utils/helper';
const columns = [
  {
    title: '标题',
    dataIndex: 'articleName',
    width: '30%',
  },
  {
    title: '文章类型',
    dataIndex: 'articleType',
    slots: {
      customRender: 'articleType',
    },
  },
  {
    title: '浏览次数',
    dataIndex: 'scanNum',
    slots: {
      customRender: 'scanNum',
    },
  },
  {
    title: '赞同数',
    dataIndex: 'thumbsUp',
    slots: {
      customRender: 'thumbsUp',
    },
  },
  {
    title: '反对数',
    dataIndex: 'thumbsDown',
    slots: {
      customRender: 'thumbsDown',
    },
  },
  {
    title: '文章添加时间',
    dataIndex: 'createTimeStr',
    slots: {
      customRender: 'createTimeStr',
    },
  },
  {
    title: '引用位置',
    dataIndex: 'referPosition',
    slots: {
      customRender: 'referPosition',
    },
  },
  {
    title: '操作',
    dataIndex: 'handler',
    slots: {
      customRender: 'handler',
    },
  },
];
const transList = list => {
  return list.map(item => {
    item.createTimeStr = parseTime(item.createTime);
    return item;
  });
};
export default defineComponent({
  name: '',
  setup() {
    // 文章搜索类型
    const articleType = reactive({
      articleType: undefined,
      keywords: '',
    });

    // 分页数据
    const pagination = reactive({ limit: 10, page: 1, total: 0 });

    /**
     * 获取文章库列表
     **/
    const state = reactive({ loading: false, dataSource: [] });
    const getList = async () => {
      try {
        state.loading = true;
        const { page } = await apiGetArticleList({
          page: pagination.page,
          limit: pagination.limit,
          articleType: articleType.articleType,
          keywords: articleType.keywords,
        });
        state.dataSource = transList(page.list);
        pagination.total = page.total;
        // 选中格为空
        selRows.value = [];
      } finally {
        state.loading = false;
      }
    };
    getList();

    /**
     * 搜索列表
     **/
    const resetPage = () => {
      pagination.page = 1;
      getList();
    };

    // 文章定义
    const articleForm = ref({
      articleName: '',
      labelId: [],
      articleType: 1,
      describeInfo: '',
      articleInfo: '',
    });

    // 删除文章弹框
    const delArticleWarning = ref(false);

    /**
     * 选中列表条数
     **/
    const selectCount = ref(0);
    // 选中行数
    let selRows = ref([]);
    const rowSelection = {
      selectedRowKeys: selRows,
      onChange: selectedRow => {
        selRows.value = selectedRow;
      },
    };

    // 控制抽屉显示隐藏
    const showArticleDraw = ref(false);

    /**
     * 弹出添加抽屉
     **/
    const add = () => {
      showArticleDraw.value = true;
      articleForm.value = {
        id: undefined,
        articleName: '',
        labelId: [],
        articleType: 1,
        describeInfo: '',
        articleInfo: '',
      };
    };

    // 删除条数
    const delCount = ref(0);

    /**
     * 弹出编辑抽屉
     **/
    const edit = id => {
      showArticleDraw.value = true;
      apiGetArticleDetail({ id }).then(res => {
        articleForm.value = res.article;
      });
    };

    // 记录当前是批量删除还是单条删除
    let delType;
    /**
     * 删除文章弹出框
     **/
    const delForm = ref({});
    const delArticle = (type, form) => {
      delType = type;
      if (type === 'one') {
        delForm.value = form;
        delCount.value = 1;
        delArticleWarning.value = true;
      } else if (selRows.value.length) {
        delArticleWarning.value = true;
        delCount.value = selRows.value.length;
      }
    };

    /**
     * 确认删除文章
     **/
    const confirmDelArticle = () => {
      if (delType === 'one') {
        delOneArticle();
      } else {
        delBatchArticle();
      }
    };

    /**
     * 删除单篇文章
     **/
    const delOneArticle = () => {
      apiDelArticle({ ids: delForm.value.id }).then(() => {
        message.success('删除成功');
        getList();
      });
    };

    /**
     * 批量删除文章
     **/
    const delBatchArticle = () => {
      const ids = concatIds(selRows.value);
      apiDelArticle({ ids }).then(() => {
        message.success('删除成功');
        getList();
        selRows.value = [];
      });
    };

    return {
      pagination,
      articleType,
      resetPage,
      columns,
      state,
      rowSelection,
      edit,
      showArticleDraw,
      articleForm,
      add,
      delArticleWarning,
      delArticle,
      confirmDelArticle,
      selectCount,
      delCount,
      listMap: {
        1: '平台文章',
        0: '外部链接',
      },
      parseTime,
      getList,
      selRows,
    };
  },
  components: {
    relevanceTable,
    articleInfo,
    WarningModal,
  },
});
</script>

<style lang="less" scoped>
.article-type {
  width: 150px;
  margin-right: 10px;
}
.line {
  margin: 10px 0;
  border-top: 1px dashed #eee;
}
.iconfont {
  font-size: 14px;
}
.icon-xiayi12px {
  margin-left: 10px;
  cursor: pointer;
}
</style>
